﻿@{
    ViewBag.Title = "Home Page";
}
Available
<ul data-bind="foreach: AllUsers, visible: AllUsers().length > 0">
    <li>
        <!--<div data-bind="click: $parent.SelectedUser">-->
        <input type="checkbox" 
               name="checkedUser" 
               data-bind="value: userId, checked:$root.selectedUserNames" />
        <span data-bind="text: userName" ></span>
        <!--</div>-->
    </li> 
</ul><br/>
Selected
<ul data-bind="foreach: SelectedUsers, visible: SelectedUsers().length > 0">
    <li>
        <span data-bind="text: userName" ></span>
    </li> 
</ul>
<script src="~/Scripts/knockout-2.1.0.js"></script>

<script>
    function User(data) {
        this.userId = data.userId;
        this.userName = data.userName;
        this.selected = data.selected;
    }


    var dataSource = [
        new User({
            userId :1,
            userName: "test1",
            selected: false
        }),
        new User({
            userId :2,
            userName: "test2",
            selected: false
        })
    ];


    function UsersViewModel() {
        var self = this;
        //initial data may have two IEnumerables
        self.AllUsers = ko.observableArray(dataSource);
        self.SelectedUsers = ko.observableArray([]);

        self.selectedUserNames = ko.observableArray([]);

        self.selectedUserNames.subscribe(function (newValue) {
            var newSelectedUserNames = newValue;
            var newSelectedUsers = [];
            ko.utils.arrayForEach(newSelectedUserNames, function (userId) {
                var selectedUser = ko.utils.arrayFirst(self.AllUsers(), function (user) {
                    return (user.userId === userId);
                });
                newSelectedUsers.push(selectedUser);
            });
            self.SelectedUsers(newSelectedUsers);
        });

        self.selected = function(data) {

        };
    }
    ko.applyBindings(new UsersViewModel());
</script>